package com.dolawing.phonecallapp.keepAliveService;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.dolawing.phonecallapp.R;
import com.dolawing.phonecallapp.listenphonecall.JobSchedulerService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * content:后台运行的服务
 */
public class LocalService extends Service {
    private MyBinder binder;
    private MyConn conn;
    private IKeepAliveService iKeepAliveService;
    private NotificationCompat.Builder builder;
    private int notifyId =2;

    private  int count = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new MyBinder();
        conn = new MyConn();
        startTo();

        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    while(true){
                        try {
                            count = (count + 1)%36000;
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        this.startService(new Intent(LocalService.this,RemoteService.class));
        this.bindService(new Intent(LocalService.this, RemoteService.class),
                conn, Context.BIND_AUTO_CREATE);
        Log.i("在LocalService服务...","onStartCommand方法执行");

        //定时器
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    while(true){
                        Calendar calendar = Calendar.getInstance();
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int min = calendar.get(Calendar.MINUTE);
                        int sec = calendar.get(Calendar.SECOND);
                        String timestamps = ""+hour + "时" + min+"分" + sec +"秒";//记录时间
                        try {
                            Thread.sleep(1000);
                            builder.setContentText("Running..."+iKeepAliveService.getServiceName()+"中,count="+iKeepAliveService.getCount());
                            startForeground(notifyId, builder.build());
                            Log.i("在LocalService服务中.....","LocalService与"+iKeepAliveService.getServiceName()+"建立链接");
                            Log.i("在LocalService服务中.....",iKeepAliveService.getServiceName()+"中，count="+iKeepAliveService.getCount());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return START_STICKY;
    }

    private class MyBinder extends IKeepAliveService.Stub {
        @Override
        public String getServiceName() throws RemoteException {
            return LocalService.class.getSimpleName();
        }

        @Override
        public int getCount() throws RemoteException {
            return count;
        }

    }

    private class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iKeepAliveService =IKeepAliveService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Intent intent = new Intent(LocalService.this, RemoteService.class);
            if (Build.VERSION.SDK_INT >= 26) {
                //适配8.0机制
                LocalService.this.startForegroundService(intent);
            } else {
                LocalService.this.startService(intent);
            }
            //绑定远程服务
            LocalService.this.bindService(new Intent(LocalService.this, RemoteService.class), conn, Context.BIND_AUTO_CREATE);

        }
    }

    private void startTo() {
        String CHANNEL_ID = "com.dolawing.phonecall.keepalive.LocalServiceId";
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel Channel = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Channel = new NotificationChannel(CHANNEL_ID, "Local Service", NotificationManager.IMPORTANCE_LOW);
            Channel.enableLights(true);
            Channel.setLightColor(Color.RED);
            Channel.setShowBadge(true);
            Channel.setDescription("LocalService");
            Channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置锁屏可见 VISIBILITY_PUBLIC=可见
            manager.createNotificationChannel(Channel);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTimes = sdf.format(new Date());
        builder = new NotificationCompat.Builder(this,CHANNEL_ID)
                .setContentTitle("Local Service,启动:"+nowTimes)//标题
                .setContentText("Running...")//内容
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher);//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

        notification = builder.build();

        //让通知显示出来 第一个参数是id，要保证每个通知所指定的id各不相同 第二个参数是Notification对象
        manager.notify(notifyId, notification);

    }

    @Override
    public void onDestroy() {
        unbindService(conn); //解绑
        super.onDestroy();
        Log.i("在LocalService服务...","onDestroy被执行");
    }

}

